package com.bite.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.contants.Constants;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.friend.domain.question.DTO.QuestionQueryDTO;
import com.bite.friend.domain.question.Question;
import com.bite.friend.domain.question.es.QuestionES;
import com.bite.friend.domain.question.vo.QuestionDetailVO;
import com.bite.friend.domain.question.vo.QuestionVO;
import com.bite.friend.elasticsearch.QuestionRepository;
import com.bite.friend.manager.QuestionCacheManager;
import com.bite.friend.mapper.question.QuestionMapper;
import com.bite.friend.mapper.user.UserSubmitMapper;
import com.bite.friend.service.question.IQuestionService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;


    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        long count =  questionRepository.count();
        //根据数量判断有没有值
        if (count <= 0){
            //刷新同步
            refreshQuestion();
        }
        //后续就查es
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //分页
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum()-1 ,questionQueryDTO.getPageSize(),sort);
        //到这里已经同步过
        //获取参数
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyWord = questionQueryDTO.getKeyWord();
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyWord)){
             questionESPage = questionRepository.findAll(pageable);
        }
        else if (StrUtil.isEmpty(keyWord)){
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        }
        else if (difficulty == null){
            questionESPage = questionRepository.findByTitleOrContent(keyWord,keyWord,pageable);
        }
        else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyWord,keyWord,difficulty,pageable);
        }
        long total = questionESPage.getTotalElements();

        if (total <= 0){
            return TableDataInfo.empty();
        }
        //
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);

        return TableDataInfo.success(questionVOList,total);
    }

    /**
     * 热榜信息
     * @return
     */
    @Override
    public List<QuestionVO> hotList() {
        //根据用户提交次数判断
        //可以从submit表中获取questionId
        //先从redis拿,拿不到...
        Long total = questionCacheManager.getHostListSize();
        List<Long> hotQuestionIdList;
        if (total == null || total <=0){
            PageHelper.startPage(Constants.HOST_QUESTION_LIST_START, Constants.HOST_QUESTION_LIST_END);
            //拿不到,从数据库查到每个questionId
             hotQuestionIdList = userSubmitMapper.selectHostQuestionList();
             //存到redis
            questionCacheManager.refreshHotQuestionList(hotQuestionIdList);
        }else {
            hotQuestionIdList = questionCacheManager.getHostList();
        }
        //根据questionId,获取题目详细信息
        return  assembleQuestionVOList(hotQuestionIdList);
    }



    /**
     * 查看答题题目数据
     * @param questionId
     * @return
     */
    @Override
    public QuestionDetailVO detail(Long questionId) {
        //先从es中查
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null){
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        //从数据库查
        Question question = questionMapper.selectById(questionId);
        if (question == null){
            return null;
        }
        //同步到es
        refreshQuestion();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        //先查列表
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0){
            questionCacheManager.refresh();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0){
            questionCacheManager.refresh();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }




    //数据刷新
    private void refreshQuestion(){
        List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questions)){
            return;
        }

        //类型转换
        List<QuestionES> questionESList = BeanUtil.copyToList(questions, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }


    /**
     * 根据题目id获取题目信息
     * @param hotQuestionIdList
     * @return
     */
    private List<QuestionVO> assembleQuestionVOList(List<Long> hotQuestionIdList) {
        if (CollectionUtil.isEmpty(hotQuestionIdList)){
            return new ArrayList<>();
        }

        List<QuestionVO> resultList = new ArrayList<>();

        //遍历id,获取title
        for (Long questionId:hotQuestionIdList){
            QuestionVO questionVO = new QuestionVO();
            //根据每个id获取详细信息
            QuestionDetailVO detail = detail(questionId);
            //设置title
            questionVO.setTitle(detail.getTitle());
            resultList.add(questionVO);
        }
        return resultList;
    }
}
